import { ts } from 'qvog-dsl';
import {
  native,
  HomeCheckHint,
} from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/unrestricted-file-upload.md';
const DESCRIPTION = 'Unrestricted file upload can lead to remote code execution, DoS, or other attacks. Always validate file type, size, and content on both client and server side.';

export default native<HomeCheckHint>()()
  .match((node): node is ts.CallExpression => {
    return ts.isCallExpression(node);
  })
  .when((node: ts.CallExpression) => {
    if (!ts.isPropertyAccessExpression(node.expression)) { return false };

    const method = node.expression.name.getText().toLowerCase();

    // uploadFile、append(...file)、formData.append(...)
    const isUploadMethod = ['upload', 'uploadfile', 'append'].includes(method);
    if (!isUploadMethod) { return false };

    const argsText = node.arguments.map(arg => arg.getText().toLowerCase()).join(' ');
    const mayContainFile = argsText.includes('file') || argsText.includes('filename') || argsText.includes('.blob');

    return mayContainFile;
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH,
  });
